package org.x.yuenovel.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.x.yuenovel.controller.dto.ResultDTO;
import org.x.yuenovel.controller.param.RegisterParam;
import org.x.yuenovel.controller.param.UserLoginParam;
import org.x.yuenovel.enums.ResultCodeEnum;
import org.x.yuenovel.service.UserInfoService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author xuezhendong
 * @date 2022/4/21 10:17 下午
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserInfoController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @PostMapping("register")
    public ResultDTO<String> register(@RequestBody @Validated RegisterParam registerParam) {
        String captchaCode = stringRedisTemplate.opsForValue().get(registerParam.getMail());
        if (ObjectUtils.isEmpty(captchaCode)) {
            return ResultDTO.error(ResultCodeEnum.EMAIL_CAPTCHA_EP);
        }
        if (ObjectUtils.isEmpty(registerParam.getCaptchaCode()) || !Objects.equals(captchaCode,
                registerParam.getCaptchaCode())) {
            return ResultDTO.error(ResultCodeEnum.EMAIL_CAPTCHA_ERROR);
        }
        boolean res = userInfoService.register(registerParam);
        return res ? ResultDTO.success("success") : ResultDTO.error(ResultCodeEnum.ERROR);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultDTO<Map<String, String>> login(@RequestBody UserLoginParam userLoginParam,
            HttpServletResponse response) {
        String token = userInfoService.login(userLoginParam.getUsername(), userLoginParam.getPassword());
        if (token == null) {
            return ResultDTO.error(ResultCodeEnum.PARAM_ERROR, "用户名或者密码错误");
        }

        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("tokenHeader", tokenHeader);
        tokenMap.put("token", token);
        response.setHeader(tokenHeader, token);
        return ResultDTO.success(tokenMap);
    }
}
